<template>
  <div class="common-layout" style="margin-top: 0px;">
    <el-container style="height: 90vh;">
      <el-header class="header">
        <div class="header-content">

          <span class="header-title"> 
            <span style="padding-right:50px ;"  v-if="classroomName" >班级名称：{{ classroomName }}</span> 
            <span>{{ classroomName ? '课程名称：' : '精品课：' }}</span>
            {{ courseDetail.courseName}}
          </span>
          <div class="button-group">
            <el-button v-if="!isPurchased" class="back-button" @click="buy" type="primary">购买</el-button>
            <el-button v-else class="back-button" disabled type="primary">已购买</el-button>
            <el-button class="back-button" @click="goBack" type="primary">返回</el-button>
          </div>
        </div>
      </el-header>
      <el-main class="main">
        <!-- 其他内容 -->
        <!-- 表格 -->
        <page-container style="width: 100%;">
          <el-table :data="videoList" height="94%" style="width: 100%">
            <el-table-column align="center" width="100px" label="序号">
              <template #default="{ $index }">
                {{ (params.pageNum - 1) * params.pageSize + $index + 1 }}
              </template>
            </el-table-column>
            <el-table-column align="left" prop="videoName" :show-overflow-tooltip="true" label="视频名称" />
            <!-- <el-table-column align="left" prop="videoDuration" :show-overflow-tooltip="true" label="视频时长" /> -->
            <el-table-column prop="videoDuration" label="视频时长" align="center" :formatter="formatDuration">
            </el-table-column>
            <el-table-column align="left" prop="createTime" :show-overflow-tooltip="true" label="创建时间" />
            <el-table-column label="操作" align="center" width="180px">
              <template #default="{ row, $index }">
                <el-button type="text" plain @click="playBack(row.videoId)" v-if="isPurchased || $index < 3">
                  {{ isPurchased ? '播放' : '试看' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
            v-model:current-page="params.pageNum" v-model:page-size="params.pageSize" :page-sizes="[10, 20, 30]"
            @size-change="handleSizeChange" @current-change="handleCurrentChange"
            style="margin:20px 100px 20px 0; justify-content: flex-end" />
        </page-container>
      </el-main>

    </el-container>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { getCourseDetailService, buyCourse, haveYouPurchased } from "@/apis/course";
import { getVideoListService } from "@/apis/video";
import router from "@/router";
const formatDuration = (row, column, cellValue) => {
  // 1. 基础类型校验
  const duration = Number(cellValue ?? 0)
  if (isNaN(duration)) return '00:00'

  // 2. 时间计算
  const hours = Math.floor(duration / 3600)
  const minutes = Math.floor((duration % 3600) / 60)
  const seconds = Math.floor(duration % 60)

  // 3. 格式标准化
  const pad = n => n.toString().padStart(2, '0')
  return hours > 0
    ? `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
    : `${pad(minutes)}:${pad(seconds)}`
}
function goBack() {
  router.go(-1);
}
const buy = async () => {
  const confirmed = window.confirm("您确定要购买该商品吗？");

  if (confirmed) {
    // 继续进行购买操作
    console.log("购买操作进行中...");
    // 在这里添加购买逻辑
    buyCourse(courseId).then(() => {
      havePurchased();
      ElMessage.success('购买成功')
    });

  } 
};

const courseDetail = reactive({});
let courseId = useRoute().query.courseId;
let classroomName = useRoute().query.classroomName;

async function getCourseDetail() {
  const res = await getCourseDetailService(courseId);
  Object.assign(courseDetail, res.data);
}

onMounted(() => {
  getCourseDetail();
});

const params = reactive({
  pageNum: 1,
  pageSize: 10,
  courseId: courseId,
})
const videoList = ref([]) //题目列表
const total = ref(0)

async function getVideoList() {
  const result = await getVideoListService(params)
  videoList.value = result.rows
  total.value = result.total
}
getVideoList()

// 分页
function handleSizeChange(newSize) {
  params.pageNum = 1
  getVideoList()
}

function handleCurrentChange(newPage) {
  getVideoList()
}

function playBack(videoId) {
  router.push(`/tims/playBack?videoId=${videoId}`)
}

const isPurchased = ref(); // 控制按钮显示的变量

// 判断是否购买
async function havePurchased() {
  const res = await haveYouPurchased(courseId);
  isPurchased.value = res.data;
}
havePurchased();

</script>

<style lang="scss" scoped>
/* 新增上传对话框样式 */
.upload-wrapper {
  :deep(.el-upload-dragger) {
    padding: 30px;
    background-color: #f8fafc;

    .el-icon--upload {
      color: #007bff;
      font-size: 48px;
      margin-bottom: 15px;
    }

    .el-upload__text {
      color: #606266;

      em {
        color: #007bff;
      }
    }

    .el-upload__tip {
      margin-top: 10px;
      color: #999;
      font-size: 12px;
    }
  }
}
.common-layout {
  background-color: #f0f4ff;

  .header {
    height: 6%;
    display: flex;
    align-items: center;
    background-color: #007bff;
    color: white;

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      width: 100%;

      .header-title {
        font-size: 20px;
      }

      .button-group {
        display: flex;

        .back-button {
          margin-left: 10px;
        }
      }
    }
  }

  .main {
    display: flex;
    justify-content: center;
    padding: 20px;

    .page-container {
      // width: 83%; // Set width to 83%
      max-width: 1200px; // Optional max width for larger screens
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .el-table {
        width: 100%;
        border: none;

        .el-table-column {
          background-color: #f9f9f9; // Improve the table's visual appeal
        }
      }

      .el-pagination {
        margin: 20px 0;
        display: flex;
        justify-content: flex-end; // Align pagination to the right
        position: relative; // Ensure positioning works correctly

        .el-pagination__sizes {
          margin-right: 10px; // Add some space between size selector and pagination
        }
      }
    }
  }
}
</style>